package org.wheel.plugins.toolkit.util.sql;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Pair;
import cn.hutool.core.map.MapUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import lombok.Getter;
import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.JdbcNamedParameter;
import net.sf.jsqlparser.expression.operators.conditional.AndExpression;
import net.sf.jsqlparser.expression.operators.relational.*;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.select.PlainSelect;
import net.sf.jsqlparser.statement.select.Select;
import org.wheel.module.core.request.ApiParam;
import org.wheel.module.core.request.ParamField;
import org.wheel.module.core.request.ParamPaging;
import org.wheel.module.core.security.EscapeType;
import org.wheel.module.core.security.SqlSecurityUtils;
import org.wheel.plugins.toolkit.jsqlparse.helper.ParamValueConvert;
import org.wheel.plugins.toolkit.jsqlparse.helper.parameter.MyBatisParameter;
import org.wheel.plugins.toolkit.sql.core.GlobalConfig;
import org.wheel.plugins.toolkit.sql.enums.SqlModel;
import org.wheel.plugins.toolkit.util.sql.request.ParamSort;
import org.wheel.plugins.toolkit.util.sql.visitor.SqlParameterReplacementHandler;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

public class SqlConditionBuilder {

    // 直接使用 LogFactory 创建日志对象，Hutool 会自动检测项目中的日志框架（优先级：Slf4j > Log4j > Logback > JDK Logging）
    private static final Log log = LogFactory.get();

    @Getter
    private final static SqlConditionBuilder instance = new SqlConditionBuilder();
    private SqlConditionBuilder(){}

    /**
     * 构建带条件的SQL，支持指定SQL模型类型
     * @param originalSql 原始SQL
     * @param apiParam 请求参数
     * @param sqlModel SQL模型类型
     * @return 带条件的完整SQL
     */
    public static MergedSqlResult buildConditionalSql(String originalSql, LinkedHashMap<String, Object> originalParams,
                                                      ApiParam apiParam, SqlModel sqlModel) throws JSQLParserException{
        String querySql = originalSql;
        LinkedHashMap<String, Object> params = null;

        String countSql = null;
        // 组装 where条件
        if(CollUtil.isNotEmpty(apiParam.getWhere())) {
            MergedSqlResult result = mergeSqlAndParameters(querySql, originalParams, apiParam.getWhere(), sqlModel);
            querySql = result.sql();
            params = result.params();
        }else {
            if(MapUtil.isNotEmpty(originalParams)){
                params = originalParams;
            }
        }
        // 添加排序
        if(CollUtil.isNotEmpty(apiParam.getOrderBy())) {
            List<ParamSort> orderBy = apiParam.getOrderBy().stream()
                    .map(item -> BeanUtil.toBean(item, ParamSort.class)).toList();
            querySql = SQLHelper.addOrder(querySql, orderBy);
        }
        // 添加分页
        ParamPaging paging = apiParam.getPaging();
        if(paging != null && paging.getPageSize() > 0){
            querySql = SQLHelper.resetSqlPageInfo(querySql, paging.getPageNum(), paging.getPageSize());
            // 因为分页了，所以前端需要总数进行分页
            countSql = SQLHelper.countSqlHandler(originalSql);
        }

        return new MergedSqlResult(querySql, countSql,  params, sqlModel);
    }

    /**
     * 构建带条件的SQL
     * 测试用，生产环境请使用 mergeSqlAndParameters 方法
     * @param originalSql 原始SQL
     * @param conditions 条件列表
     * <pre>{@code
     *  [
     *   {
     *     "field": "sp_type",
     *     "connector": "eq",
     *     "value": "PGAS"
     *   },
     *   {
     *     "field": "county",
     *     "connector": "in",
     *     "value": [1, 2, 3]
     *   },
     *   {
     *     "field": "alertlevel",
     *     "connector": "eq",
     *     "value": "3"
     *   }
     * ]
     * }
     * </pre>
     * @return 带条件的完整SQL
     */
    public static String buildConditionalSql(String originalSql, List<ParamField> conditions)
            throws JSQLParserException {
        return buildConditionalSql(originalSql, conditions, SqlModel.getDefaultModel());
    }
    /**
     * 构建带条件的SQL，支持指定SQL模型类型
     * 测试用，生产环境请使用 mergeSqlAndParameters 方法
     * @param originalSql 原始SQL
     * @param conditions 条件列表
     * @param sqlModel SQL模型类型
     * @return 带条件的完整SQL
     */
    public static String buildConditionalSql(String originalSql, List<ParamField> conditions, SqlModel sqlModel)
            throws JSQLParserException {
        return mergeSqlAndParameters(originalSql, null, conditions, sqlModel).sql();
    }
    /**
     * 合并SQL和参数，处理原有参数和新增参数
     * @param originalSql 原始SQL
     * @param originalParams 内部原有参数
     * @param conditions 外部新增条件
     * <pre>{@code
     *  [
     *   {
     *     "field": "sp_type",
     *     "connector": "eq",
     *     "value": "PGAS"
     *   },
     *   {
     *     "field": "county",
     *     "connector": "in",
     *     "value": [1, 2, 3]
     *   },
     *   {
     *     "field": "alertlevel",
     *     "connector": "eq",
     *     "value": "3"
     *   }
     * ]
     * }
     * </pre>
     * @param sqlModel SQL模型
     * @return 合并后的SQL和参数
     */
    public static MergedSqlResult mergeSqlAndParameters(String originalSql, LinkedHashMap<String, Object> originalParams,
                                                        List<ParamField> conditions, SqlModel sqlModel) throws JSQLParserException {
        if (CollUtil.isEmpty(conditions) && sqlModel != SqlModel.DIRECT_SQL) {
            // 没有新增条件，直接返回原始SQL和参数
            return new MergedSqlResult(originalSql, null, originalParams, sqlModel);
        }

        /*
         * 以下步骤逻辑：
         *  1 - 验证SQL是标准SQL
         *  1.1 - 如果不是标准SQL（mybatis，自定义类型），需要将sql转换成标准SQL（内部使用 :{propertyName}），并返回替换的参数名称和参数值
         *  1.1.1 - 内部使用 :{propertyName} 方式，调用{@code handleNamedParameterSqlMode}
         *  1.1.2 - 将命名参数替换成目标占位符
         *  1.2 - 如果是标准SQL，则直接调用{@code handleNamedParameterSqlMode}
         */
        // 优先强制转换SQL为命名参数
        Map<String, String>  parametersmap = SqlParameterReplacementHandler.extractNamedParametersMap(originalSql);
        String newSql = originalSql;
        if (MapUtil.isNotEmpty(parametersmap)) {
            for (Map.Entry<String, String> entry : parametersmap.entrySet()) {
                String key = SqlSecurityUtils.escape(entry.getKey(), EscapeType.REGEX);
                newSql = newSql.replaceAll(key, (new JdbcNamedParameter(entry.getValue())).toString());
            }
        }

        return switch (sqlModel) {
            case MYBATIS, CUSTOM_0, CUSTOM_1 ->
                // MYBATIS 模式SQL要特殊处理，否则调用 handleNamedParameterSqlMode 会出现 SQL 解析错误
                    instance.handleMybatisSqlMode(newSql, originalParams, conditions, sqlModel);
            default ->
                // 其他模式使用命名参数处理
                    instance.handleNamedParameterSqlMode(newSql, originalParams, conditions, sqlModel);
        };
    }

    private MergedSqlResult handleMybatisSqlMode(String newSql, LinkedHashMap<String, Object> originalParams,
                                                 List<ParamField> conditions, SqlModel targetSqlModel) throws JSQLParserException {
        // 用 :{propertyName} 标准SQL处理参数
        MergedSqlResult result = handleNamedParameterSqlMode(newSql, originalParams, conditions, SqlModel.PROPERTY_NAME);

        // 用 #{propertyName} 替换 :{propertyName}
        String resultSql = result.sql();
        for (Map.Entry<String, Object> entry : result.params().entrySet()) {
            String val = null;
            if(targetSqlModel == SqlModel.MYBATIS){
                val = (new MyBatisParameter(entry.getKey())).toString();
            } else if(targetSqlModel == SqlModel.CUSTOM_0){
                val = String.format(targetSqlModel.getSqlFormat(), entry.getKey());
            } else {
                log.warn("暂不支持的SQL模型：%s, 使用默认模式处理参数", targetSqlModel.name());
                val = String.format(targetSqlModel.getSqlFormat(), entry.getKey());
            }
            resultSql = resultSql.replaceAll((new JdbcNamedParameter(entry.getKey())).toString(), val);
        }
        return new MergedSqlResult(resultSql, null, result.params(), targetSqlModel);
    }
    /**
     * 处理命名参数SQL模式（包括PROPERTY_NAME和MYBATIS）
     * @param originalSql
     * @param originalParams 原有参数, key 为参数名, value 为参数值，value可能为数组或集合等类型
     * @param conditions 通过外部接口传递的新增条件，格式为：WhereFields对象，重要的非空字段包含field、connector和value三个属性
     * @param sqlModel 目标要转换的SQL模型
     * @return 处理后的SQL和参数，Kye: SQL语句， Value 为参数对象
     * Value 返回的 {@code LinkedHashMap<String, Object>} ，如果是SQL模式是原生格式或Number数值格式，返回的map格式为：<pre>{@code
     * {
     *   "1": {"fieldName": "value"},
     *   "2": { "key_1": [1, 2, 3]},
     *   "3": { "key_2: "xxxxxxxx"}
     * }}</pre>
     * 如果是其他SQL模式，返回的map格式为：<pre>{@code
     * {
     *   "fieldName": "value",
     *   "key_1": [1, 2, 3],
     *   "key_2: "xxxxxxxx"
     * }
     * }</pre>
     * @throws JSQLParserException
     */
    private MergedSqlResult handleNamedParameterSqlMode(String originalSql, LinkedHashMap<String, Object> originalParams,
                                                               List<ParamField> conditions, SqlModel sqlModel) throws JSQLParserException {
        // 0. 初始化参数返回对象
        LinkedHashMap<String, Object> params = new LinkedHashMap<>();
        // 1. 解析原始SQL中的命名参数
        boolean isRowComparison = RowComparisonExpander.isRowComparison(originalSql);
        List<ParamField> existFields = null;
        String lowerSql = null;
        if(isRowComparison) {
            lowerSql = RowComparisonExpander.expand(originalSql); // SQL降级处理
            existFields = SqlParameterReplacementHandler.extractNativeParameterInfo(lowerSql);
        }else{
            existFields = SqlParameterReplacementHandler.extractNativeParameterInfo(originalSql);
        }
        // 1-2. 获取已存在的参数名称
        Set<String> existingParams = existFields.stream().map(ParamField::getField).collect(Collectors.toSet());

        // 2. 分离已存在的参数和新增参数
        List<ParamField> existingConditions = new ArrayList<>();
        List<ParamField> newConditions = new ArrayList<>();

        if(CollUtil.isNotEmpty(originalParams)){
            existingConditions.addAll(originalParams.entrySet().stream().map(entry -> ParamField.builder()
                    .field(entry.getKey()).value(entry.getValue()).connector("eq").skip(false).sno(0).build()).toList());
        }

        if(CollUtil.isNotEmpty(conditions)) {
            for (ParamField condition : conditions) {
                String field = condition.getField();
                if (existingParams.contains(field)) {
                    existingConditions.add(condition);
                } else {
                    newConditions.add(condition);
                }
            }
        }

        // 3. 使用Visitor模式替换参数
        String mergedSql = originalSql;
        if (!existingConditions.isEmpty()) {
            if(sqlModel == SqlModel.DIRECT_SQL) {
                LinkedHashMap<String, Object> finalParams = params;
                existingConditions.forEach(item->{
                    finalParams.put(item.getField(), item.getValue());
                });
                mergedSql = ParamValueConvert.convertValuesIntoSql(mergedSql, finalParams, GlobalConfig.getDialect());
            }else {
                String targetSql = mergedSql;
                if(isRowComparison){
                    targetSql = lowerSql;
                }
                Pair<String, LinkedHashMap<String, Object>> pair = SqlParameterReplacementHandler.replaceParameters(targetSql, existingConditions, sqlModel, existingParams);
                mergedSql = pair.getKey();
                params = pair.getValue(); // 得到原sql中的参数
            }
            log.debug("params:" + params);
        }


        // 4. 解析处理后的SQL
        Statement statement = CCJSqlParserUtil.parse(mergedSql);
        if (!(statement instanceof Select select)) {
            throw new IllegalArgumentException("Only SELECT statements are supported");
        }

        PlainSelect plainSelect = select.getPlainSelect();

        // 5. 构建新增条件表达式
        int startKeyIndex = SQLHelper.resolveParameters(params).length;
        Expression newConditionExpr = buildWhereExpression(newConditions, sqlModel, startKeyIndex);

        // 6. 合并WHERE条件
        if (newConditionExpr != null) {
            if (plainSelect.getWhere() != null) {
                newConditionExpr = new AndExpression(plainSelect.getWhere(), newConditionExpr);
            }
            plainSelect.setWhere(newConditionExpr);
        }

        // 7. 构建合并后的SQL
        mergedSql = plainSelect.toString();

        // 8. 构建参数映射
        LinkedHashMap<String, Object> mergedParams = new LinkedHashMap<>();
        // 添加已存在条件的参数（这些参数在原始SQL中已存在，但可能不在originalParams中）
        if (MapUtil.isNotEmpty(params)) {
            mergedParams.putAll(params);
        }

        // 添加新增条件的参数
        startKeyIndex = SQLHelper.resolveParameters(mergedParams).length;
        LinkedHashMap<String, Object> newConditionParams = buildConditionParameters(newConditions, sqlModel, startKeyIndex, true);
        mergedParams.putAll(newConditionParams);

        return new MergedSqlResult(mergedSql, null, mergedParams, sqlModel);
    }

    /**
     * 构建 WHERE 表达式
     * @param conditions 条件列表
     * @param sqlModel SQL模型
     * @param startKeyIndex 参数起始索引，主要针对 Native 和 Number 模式，原SQL中有参数模型，前面的参数索引可能已经占用。
     * @return
     */
    private Expression buildWhereExpression(List<ParamField> conditions, SqlModel sqlModel, int startKeyIndex) {
        if (CollUtil.isEmpty(conditions)) {
            return null;
        }

        Expression finalExpr = null;
        // 用于NUMBER类型索引计数
        AtomicInteger parameterIndex = new AtomicInteger(1+startKeyIndex);

        for (ParamField condition : conditions) {
            String field = condition.getField();
            String connector = condition.getConnector();
            Object value = condition.getValue();

            Expression currentExpr = buildSingleCondition(field, connector, value, sqlModel, parameterIndex);
            if (currentExpr != null) {
                if (finalExpr == null) {
                    finalExpr = currentExpr;
                } else {
                    finalExpr = new AndExpression(finalExpr, currentExpr);
                }
            }
        }
        return finalExpr;
    }

    /**
     * 构建新增条件的参数（使用字段名作为参数名）
     * @param conditions 条件列表
     * @param sqlModel SQL模型
     * @param startKeyIndex 参数起始索引，主要针对 Native 和 Number 模式，原SQL中有参数模型，前面的参数索引可能已经占用。
     * @param isAddKeyIndex 是否索引值，在startKeyIndex 之后开始索引。为了避免索引作为key值重复，导致参数覆盖
     * @return {@code LinkedHashMap<String, Object>} 参数映射集合。
     * 返回的 LinkedHashMap ，如果是SQL模式是原生格式或Number数值格式，返回的map格式为：<pre>{@code
     * {
     *     "1": {"fieldName": "value"},
     *     "2": { "key_1": [1, 2, 3]},
     *     "3": { "key_2: "xxxxxxxx"}
     * }}</pre>
     * 如果是其他SQL模式，返回的map格式为：<pre>{@code
     * {
     *    "fieldName": "value",
     *    "key_1": [1, 2, 3],
     *    "key_2: "xxxxxxxx"
     * }
     * }</pre>
     */
    public LinkedHashMap<String, Object> buildConditionParameters(List<ParamField> conditions, SqlModel sqlModel, int startKeyIndex, boolean isAddKeyIndex) {
        if (CollUtil.isEmpty(conditions)) {
            return new LinkedHashMap<>();
        }

        LinkedHashMap<String, Object> conditionParams = new LinkedHashMap<>();

        for (int i = 0; i < conditions.size(); i++) {
            ParamField condition = conditions.get(i);

            String connector = condition.getConnector();

            String field = condition.getField();
            Object value = condition.getValue();

            switch (connector.toLowerCase()) {
                case "eq":
                case "=":
                case "ne":
                case "<>":
                case "!=":
                case "gt":
                case ">":
                case "ge":
                case "gte":
                case ">=":
                case "lt":
                case "<":
                case "le":
                case "lte":
                case "<=":
                    mergeParams(conditionParams, field, value, sqlModel, startKeyIndex, isAddKeyIndex);
                    break;
                case "leftlike":
                    mergeParams(conditionParams, field, "%" + value, sqlModel, startKeyIndex, isAddKeyIndex);
                    break;
                case "rightlike":
                    mergeParams(conditionParams, field, value + "%", sqlModel, startKeyIndex, isAddKeyIndex);
                    break;
                case "like":
                    mergeParams(conditionParams, field, "%" + value + "%", sqlModel, startKeyIndex, isAddKeyIndex);
                    break;
                case "in":
                case "notin":
                    mergeParams(conditionParams, field, value, sqlModel, startKeyIndex, isAddKeyIndex);
                    break;
                case "between":
                    if (value instanceof List && ((List<?>) value).size() == 2) {
                        List<?> values = (List<?>) value;
                        mergeParams(conditionParams, field + "_start", values.get(0), sqlModel, startKeyIndex, isAddKeyIndex);
                        mergeParams(conditionParams, field + "_end", values.get(1), sqlModel, startKeyIndex, isAddKeyIndex);
                    }
                    break;
                default:
                    throw new IllegalArgumentException("Unsupported connector: " + connector);
            }
        }

        return conditionParams;
    }

    private void mergeParams(LinkedHashMap<String, Object> conditionParams, String key, Object value, SqlModel sqlModel, int startKeyIndex, boolean isAddKeyIndex){
        SqlParameterReplacementHandler.paramMapHandle(conditionParams, Map.of(key, value), sqlModel, startKeyIndex, isAddKeyIndex);
    }

    /**
     * 构建单个条件表达式
     * 复用where包下的条件构建逻辑
     */
    private Expression buildSingleCondition(String field, String connector, Object value, SqlModel sqlModel, AtomicInteger parameterIndex) {
        // 验证字段名是否合法
        if (!SqlSecurityUtils.isValidFieldName(field)) {
            throw new SecurityException("非法字段名: " + field);
        }
        
        // 验证操作符是否合法
        if (!SqlSecurityUtils.isValidOperator(connector)) {
            throw new SecurityException("非法操作符: " + connector);
        }
        
        Column column = new Column(field);

        switch (connector.toLowerCase()) {
            case "eq":
            case "=":
                return new EqualsTo(column, convertToPlaceholderExpression(value, sqlModel, field, parameterIndex));
            case "ne":
            case "<>":
            case "!=":
                return new NotEqualsTo(column, convertToPlaceholderExpression(value, sqlModel, field, parameterIndex));
            case "gt":
            case ">":
                return new GreaterThan(column, convertToPlaceholderExpression(value, sqlModel, field, parameterIndex));
            case "ge":
            case "gte":
            case ">=":
                return new GreaterThanEquals(column, convertToPlaceholderExpression(value, sqlModel, field, parameterIndex));
            case "lt":
            case "<":
                return new MinorThan(column, convertToPlaceholderExpression(value, sqlModel, field, parameterIndex));
            case "le":
            case "lte":
            case "<=":
                return new MinorThanEquals(column, convertToPlaceholderExpression(value, sqlModel, field, parameterIndex));
            case "leftlike":
                return new LikeExpression()
                        .withLeftExpression(column)
                        .withRightExpression(convertToPlaceholderExpression("%" + value, sqlModel, field, parameterIndex));
            case "rightlike":
                return new LikeExpression()
                        .withLeftExpression(column)
                        .withRightExpression(convertToPlaceholderExpression(value + "%", sqlModel, field, parameterIndex));
            case "like":
                return new LikeExpression()
                        .withLeftExpression(column)
                        .withRightExpression(convertToPlaceholderExpression("%" + value + "%", sqlModel, field, parameterIndex));
            case "in":
                if (value instanceof List) {
                    // 对于PROPERTY_NAME模式，使用单个参数名，让NamedParameterJdbcTemplate自动处理
                    if (sqlModel == SqlModel.PROPERTY_NAME) {
                        return new InExpression(
                                column,
                                new ParenthesedExpressionList<>(convertToPlaceholderExpression(value, sqlModel, field, parameterIndex))
                        );
                    } else {
                        // 其他模式需要展开参数
                        return new InExpression(
                                column,
                                new ParenthesedExpressionList<>(convertToPlaceholderExpressionArray((List<?>) value, sqlModel, field, parameterIndex))
                        );
                    }
                }
                break;
            case "notin":
                if (value instanceof List) {
                    // 对于PROPERTY_NAME模式，使用单个参数名，让NamedParameterJdbcTemplate自动处理
                    if (sqlModel == SqlModel.PROPERTY_NAME) {
                        InExpression inExpr = new InExpression(
                                column,
                                new ParenthesedExpressionList<>(convertToPlaceholderExpression(value, sqlModel, field, parameterIndex))
                        );
                        inExpr.setNot(true);
                        return inExpr;
                    } else {
                        // 其他模式需要展开参数
                        InExpression inExpr = new InExpression(
                                column,
                                new ParenthesedExpressionList<>(convertToPlaceholderExpressionArray((List<?>) value, sqlModel, field, parameterIndex))
                        );
                        inExpr.setNot(true);
                        return inExpr;
                    }
                }
                break;
            case "between":
                if (value instanceof List && ((List<?>) value).size() == 2) {
                    List<?> range = (List<?>) value;
                    return new Between()
                            .withLeftExpression(column)
                            .withBetweenExpressionStart(convertToPlaceholderExpression(range.get(0), sqlModel, field, parameterIndex))
                            .withBetweenExpressionEnd(convertToPlaceholderExpression(range.get(1), sqlModel, field, parameterIndex));
                }
                break;
            default:
                throw new IllegalArgumentException("Unsupported connector: " + connector);
        }

        return null;
    }

    /**
     * 将值转换为占位符表达式
     * 复用ParamValueConvert类中的方法处理参数
     */
    private Expression convertToPlaceholderExpression(Object value, SqlModel sqlModel, String fieldName, AtomicInteger parameterIndex) {
        return SqlParameterReplacementHandler.convertToPlaceholderExpression(value, sqlModel, fieldName, parameterIndex);
    }

    /**
     * 将列表转换为占位符表达式数组
     */
    private Expression[] convertToPlaceholderExpressionArray(List<?> values, SqlModel sqlModel, String fieldName, AtomicInteger parameterIndex) {
        return values.stream()
                .map(value -> convertToPlaceholderExpression(value, sqlModel, fieldName, parameterIndex))
                .toArray(Expression[]::new);
    }


    /**
     * 对外提供的方法。将当前 MergedSqlResult 返回的参数，按SQL模式要求进行转换
     * @param params 原始参数,仅将当前 MergedSqlResult 返回的参数，按SQL模式进行处理。
     *               传入参数样例：
     * <pre>{@code
     * {
     *     "1": {
     *         "key_1": "XXXXXXXXXX"
     *     },
     *     "2": {
     *         "key_2": [
     *             "XXXX预警",
     *             "XXXX报警"
     *         ]
     *     }
     * }
     * }</pre>
     * @param sqlModel 要转换的SQL参数模式
     * @return 转换后的参数Map，key为参数名，value为参数值
     */
    public static LinkedHashMap<String, Object> convertParameters(LinkedHashMap<String, Object> params, SqlModel sqlModel) {
        LinkedHashMap<String, Object> mergedParams = new LinkedHashMap<>();
        if(sqlModel == SqlModel.NATIVE || sqlModel == SqlModel.NUMBER){
            Object[] nativeSqlParams = SQLHelper.resolveParameters(params);
            for (int i = 0; i < nativeSqlParams.length; i++) {
                mergedParams.put(String.valueOf(i+1), nativeSqlParams[i]);
            }
        } else if(sqlModel == SqlModel.PROPERTY_NAME || sqlModel == SqlModel.MYBATIS){
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                Map<String, Object> value = (Map<String, Object>)entry.getValue();
                mergedParams.put(entry.getKey(), value.get(entry.getKey()));
            }
        } else{
            mergedParams = params;
        }
        return mergedParams;
    }

    /**
     * 合并后的SQL结果
     */
    public record MergedSqlResult(String sql, String countSql, LinkedHashMap<String, Object> params, SqlModel sqlModel) {}
}
